package com.yoke.controller.api;

import com.alibaba.druid.util.JdbcUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yoke.common.JsonMessage;
import com.yoke.common.base.AbstractBaseControl;
import com.yoke.common.interceptor.NotLogin;
import com.yoke.database.DatabaseContextHolder;
import com.yoke.system.SystemBean;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.JsonUtil;
import com.yoke.util.StringUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.sql.DataSource;
import java.io.File;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by jiangzeyin on 2017/5/16.
 */
@Controller
public class ApiControl extends AbstractBaseControl {
    /**
     * 下单接口
     *
     * @param customer 客户名
     * @param gid      广告位
     * @param product  产品名
     * @param source   来源
     * @return json
     */
    @RequestMapping(value = "api/order.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    public String data(String customer, String gid, String product, String source, String gzid) {
        customer = convertFilePath(customer);
        product = convertFilePath(product);
        File customerFile = new File(getConfFile(), customer);
        if (!customerFile.exists() || !customerFile.isDirectory())
            return JsonMessage.getString(100, "提交失败，请正确使用订单系统");
        File fileProduct = new File(customerFile, product);
        if (!fileProduct.exists() || !fileProduct.isDirectory())
            return JsonMessage.getString(101, "提交失败，请正确使用订单系统");
        File productConf = new File(customerFile, "product.conf");
        if (!productConf.exists() || productConf.isDirectory())
            return JsonMessage.getString(102, "提交失败，订单系统异常");
        JSONArray jsonArray;
        try {
            jsonArray = (JSONArray) JsonUtil.readJson(productConf.getPath());
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("订单失败", e);
            return JsonMessage.getString(103, "提交失败，订单系统异常!");
        }
        if (jsonArray == null)
            return JsonMessage.getString(104, "提交失败，订单系统异常!");
        String tableName = null;
        String orderType = null;
        for (int i = jsonArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            if (product.equals(name)) {
                tableName = jsonObject.getString("tableName");
                orderType = jsonObject.getString("orderType");
                break;
            }
        }
        if (tableName == null || orderType == null)
            return JsonMessage.getString(105, "提交失败，订单系统异常!");
        File orderTypeFile = new File(getOrderTypeFile());
        if (!orderTypeFile.exists() || orderTypeFile.isDirectory())
            return JsonMessage.getString(106, "提交失败，订单系统异常!");
        JSONArray orderTypeArray;
        try {
            orderTypeArray = (JSONArray) JsonUtil.readJson(orderTypeFile.getPath());
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("订单失败", e);
            return JsonMessage.getString(107, "提交失败，订单系统异常!");
        }
        if (orderTypeArray == null)
            return JsonMessage.getString(108, "提交失败，订单系统异常!");
        JSONArray tableInfo = null;
        for (int i = orderTypeArray.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = orderTypeArray.getJSONObject(i);
            String name = jsonObject.getString("name");
            if (orderType.equals(name)) {
                tableInfo = jsonObject.getJSONArray("table");
                break;
            }
        }
        if (tableInfo == null || tableInfo.size() < 1)
            return JsonMessage.getString(109, "提交失败，订单系统异常!");
        StringBuffer columns = new StringBuffer();
        List<Object> parameters = new LinkedList<>();
        for (int i = tableInfo.size() - 1; i >= 0; i--) {
            JSONObject jsonObject = tableInfo.getJSONObject(i);
            if (columns.length() >= 1)
                columns.append(",");
            String name = jsonObject.getString("name");
            columns.append(name);
            String parName = jsonObject.getString("parName");
            String value = getParameter(parName, "");
            parameters.add(value);
        }
        columns.append(",ip");
        parameters.add(ip);
        columns.append(",source");
        parameters.add(source);
        columns.append(",gid");
        // 处理广告位
        if (StringUtil.IsEmpty(gid))
            gid = gzid;
        parameters.add(gid);
        columns.append(",uga");
        parameters.add(getUserAgent());
        String sql = String.format("insert into %s(%s,createTime) values(%s,UNIX_TIMESTAMP(NOW()))", tableName, columns, get(parameters.size()));
        SystemLog.LOG().info(sql);
        DataSource dataSource = DatabaseContextHolder.getDataSource();
        try {
            JdbcUtils.execute(dataSource, sql, parameters);
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("下单失败", e);
            return JsonMessage.getString(100, "下单失败，请稍等重试");
        }
        return JsonMessage.getString(200, "下单成功");
    }

    /**
     * 跨域订单信息
     *
     * @param customer 客户名
     * @param gid      gid
     * @param product
     * @param source
     * @param gzid
     * @return
     */
    @RequestMapping(value = "api2/order.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    @NotLogin
    @CrossOrigin
    public String api2(String customer, String gid, String product, String source, String gzid) {
        return data(customer, gid, product, source, gzid);
    }

    private String get(int count) {
        StringBuilder sql = new StringBuilder();
        for (int i = 0; i < count; i++) {
            if (i > 0)
                sql.append(",");
            sql.append("?");
        }
        return sql.toString();
    }

    private String getConfPath() {
        return String.format("%s/%s", SystemBean.getInstance().getEnvironment().getProperty("order.conf"), "conf/customer");
    }

    private String getOrderTypeFile() {
        return String.format("%s/%s", SystemBean.getInstance().getEnvironment().getProperty("order.conf"), "/conf/ordertype/type.conf");
    }

    private File getConfFile() {
        return new File(getConfPath());
    }
}
